<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {

            height: 405px;
            border: 1px solid #000;
            background: url(./0143455c1520d6a80121ab5d734bb5.jpg@1280w_1l_2o_100sh.jpg) no-repeat 0px -500px;
            position: relative;

        }

        #fly {
            width: 50px;
            height: 50px;
            background-color: red;
            position: absolute;
            left: 200px;
            bottom: 100px;
        }
    </style>
</head>

<body>
    <div id="box">
        <div id="fly"></div>
    </div>

    <script>
        let box = document.getElementById("box");
        let fly = document.getElementById("fly");

        let num = 0
        setInterval(() => {
            num++
            if (num >= 1000) { num = 0 }
            box.style.backgroundPosition = '0px' + (-500 + num) + "px"

        }, 100)


        window.document.onkeydown = function (e) {
            let e = e || window.event;
            console.log(e.keyCode);

            // 向前
            if (e.keyCode == 38) {
                let top = fly.offsetTop - 10
                console.log(top);

                if (top <= 20) { top = 20 }
                fly.style.top = top + "px"
            }
            // 向后
            if (e.keyCode == 40) {
                let top = fly.offsetTop + 10
                if (top >= 420) { top = 420 }
                fly.style.top = top + "px"
            }
            // 向左
            if (e.keyCode == 37) {
                let left = fly.offsetLeft - 10

                if (left <= 20) { left = 20 }
                fly.style.left = left + "px"
            }
            // 向右
            if (e.keyCode == 39) {
                let left = fly.offsetLeft + 10
                if (left >= 420) { left = 420 }
                fly.style.left = left + "px"
            }
        }

    </script>
</body>

</html>